package com.dsl.dslsuzhou.controller;

import com.dsl.dslsuzhou.service.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 元数据查询控制器
 * 提供维度表信息查询接口，便于前端动态构造DSL查询参数
 */
@RestController
@RequestMapping("/api/${api-module}/metadata")
@CrossOrigin(origins = "*")
public class MetadataController {

    @Autowired
    private MetadataService metadataService;

    /**
     * 查询所有子系统信息
     * @return 子系统列表，包含ID、名称、类型、父级ID
     */
    @GetMapping("/subsystems")
    public ResponseEntity<Map<String, Object>> getSubsystems() {
        try {
            Map<String, Object> result = metadataService.getAllSubsystems();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse(500, "查询子系统信息失败: " + e.getMessage()));
        }
    }

    /**
     * 按类型分组查询子系统
     * @return 按类型分组的子系统信息
     */
    @GetMapping("/subsystems/by-type")
    public ResponseEntity<Map<String, Object>> getSubsystemsByType() {
        try {
            Map<String, Object> result = metadataService.getSubsystemsByType();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse(500, "查询子系统类型信息失败: " + e.getMessage()));
        }
    }

    /**
     * 查询特定类型的子系统ID列表
     * @param type 子系统类型（如：耗电、用水）
     * @return 该类型下所有子系统的ID列表
     */
    @GetMapping("/subsystems/ids-by-type")
    public ResponseEntity<Map<String, Object>> getSubsystemIdsByType(@RequestParam String type) {
        try {
            Map<String, Object> result = metadataService.getSubsystemIdsByType(type);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse(500, "查询子系统ID失败: " + e.getMessage()));
        }
    }

    /**
     * 创建错误响应的辅助方法
     */
    private Map<String, Object> createErrorResponse(int code, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("message", message);
        response.put("data", null);
        return response;
    }
}
